package com.lizard.schedule.service;

import android.text.TextUtils;

import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataItem;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.WearableListenerService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lizard.schedule.consts.Path;
import com.lizard.schedule.manager.ObserverManager;
import com.lizard.schedule.model.WearSchedule;

import java.util.List;

/**
 * Created by wangyiqian on 16/6/5.
 */

public class DataLayerListenerService extends WearableListenerService {

    @Override
    public void onDataChanged(DataEventBuffer dataEvents) {
        super.onDataChanged(dataEvents);

        if(dataEvents == null){
            return;
        }

        for (DataEvent event : dataEvents) {
            if (event.getType() == DataEvent.TYPE_CHANGED) {

                DataItem item = event.getDataItem();

                if (item.getUri().getPath().compareTo(Path.CMD_SEND_SCHEDULES) == 0) {
                    DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
                    String data = dataMap.getString("data");

                    if(!TextUtils.isEmpty(data)){

                        java.lang.reflect.Type type = new TypeToken<List<WearSchedule>>(){}.getType();
                        final List<WearSchedule> wearSchedules = new Gson().fromJson(data, type);

                        if(wearSchedules != null){
                            ObserverManager.getInstance().notifyOnSyncSchedulesListeners(wearSchedules);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void onMessageReceived(MessageEvent messageEvent) {
        super.onMessageReceived(messageEvent);
    }

    /**
     * 与手机建立连接
     *
     * @param peer
     */
    @Override
    public void onPeerConnected(Node peer) {
        super.onPeerConnected(peer);
        ObserverManager.getInstance().notifyHandsetConnectChangedListeners(true, peer);
    }

    /**
     * 与手机连接中断
     *
     * @param peer
     */
    @Override
    public void onPeerDisconnected(Node peer) {
        super.onPeerDisconnected(peer);
        ObserverManager.getInstance().notifyHandsetConnectChangedListeners(false, peer);

    }
}
